<template>
	<view class="container">
		<!-- 收货地址 -->
		<view class="address-card" @click="selectAddress">
			<view v-if="address" class="address-info">
				<view class="address-header">
					<text class="name">{{address.name}}</text>
					<text class="phone">{{address.phone}}</text>
				</view>
				<view class="address-detail">
					<text>{{address.province}} {{address.city}} {{address.district}} {{address.address}}</text>
				</view>
			</view>
			<view v-else class="no-address">
				<text>请选择收货地址</text>
			</view>
			<u-icon name="arrow-right" color="#999" size="28"></u-icon>
		</view>
		
		<!-- 商品列表 -->
		<view class="product-list">
			<view class="section-title">商品信息</view>
			<view class="product-item" v-for="(item, index) in orderData.products" :key="index">
				<image class="product-image" :src="item.thumbnail" mode="aspectFill"></image>
				<view class="product-info">
					<view class="product-name">{{item.name}}</view>
					<view class="product-price">
						<text>¥{{item.price}}</text>
					</view>
				</view>
				<view class="product-quantity">x{{item.quantity}}</view>
			</view>
		</view>
		
		<!-- 积分抵扣 -->
		<view class="points-section">
			<view class="section-title">积分抵扣</view>
			<view class="points-content">
				<view class="points-toggle">
					<view class="points-info">
						<text>积分抵扣</text>
						<text class="points-available">可用积分: {{userInfo.points || 0}}积分 (可抵扣¥{{maxPointsDiscount.toFixed(2)}})</text>
					</view>
					<switch 
						:checked="usePointsEnabled" 
						color="#007aff" 
						@change="togglePointsUsage"
					/>
				</view>
			</view>
		</view>
		
		<!-- 支付方式 -->
		<view class="payment-section">
			<view class="section-title">支付方式</view>
			<view class="payment-options">
				<view class="payment-option" 
					:class="{'active': paymentType === 0}" 
					@click="selectPaymentType(0)">
          <view style="display: flex;align-items: center;">
            <image style="width: 50rpx;height: 50rpx;margin-right: 12rpx" src="/static/wallet/wxpay.png"  />
            <text>微信支付</text>
          </view>
					<u-icon v-if="paymentType === 0" name="checkmark-circle-fill" color="#007aff" size="32"></u-icon>
				</view>
			</view>
		</view>
		
		<!-- 订单备注 -->
		<view class="remark-section">
			<view class="section-title">订单备注</view>
			<u-input style="margin: 0 20rpx" v-model="remark" placeholder="请输入订单备注（选填）" border="bottom"></u-input>
		</view>
		
		<!-- 订单金额 -->
		<view class="order-amount">
			<view class="amount-item">
				<text>商品金额</text>
				<text>¥{{totalPrice.toFixed(2)}}</text>
			</view>
			<view class="amount-item" v-if="shipping > 0">
				<text>运费</text>
				<text>¥{{shipping.toFixed(2)}}</text>
			</view>
			<view class="amount-item" v-if="pointsDiscount > 0">
				<text>积分抵扣</text>
				<text class="discount-price">-¥{{pointsDiscount.toFixed(2)}}</text>
			</view>
			<view class="amount-item points-detail" v-if="pointsDiscount > 0">
				<text class="points-used-text">使用{{pointsUsed}}积分，抵扣¥{{pointsDiscount.toFixed(2)}}（100积分=1元）</text>
			</view>
			<view class="amount-item total">
				<text>实付金额</text>
				<text class="total-price">¥{{finalPrice.toFixed(2)}}</text>
			</view>
		</view>
		
		<!-- 底部提交栏 -->
		<view class="footer">
			<view class="footer-price">
				<text>合计：</text>
				<text class="price">¥{{finalPrice.toFixed(2)}}</text>
			</view>
			<view class="submit-btn" @click="submitOrder">提交订单</view>
		</view>
	</view>
</template>

<script>
import { mapGetters } from 'vuex'
	export default {
		data() {
			return {
				orderData: {
					products: []
				},
				address: null,
				paymentType: 0, // 0: 微信支付
				remark: '',
				shipping: 0, // 运费
				totalPrice: 0,
				usePointsEnabled: false, // 是否启用积分抵扣
				pointsDiscount: 0, // 积分抵扣金额
			}
		},
    computed: {
      ...mapGetters(['userInfo']),
			// 最大可用积分抵扣金额
			maxPointsDiscount() {
				const maxPoints = this.userInfo.points || 0;
				// 100积分 = 1元
				const maxDiscount = maxPoints / 100;
				// 不能超过商品总价
				return Math.min(maxDiscount, this.totalPrice);
			},
			// 使用的积分数量
			pointsUsed() {
				return this.usePointsEnabled ? Math.round(this.pointsDiscount * 100) : 0;
			},
			// 最终支付金额 = 商品总价 + 运费 - 积分抵扣
			finalPrice() {
				return Math.max(0, this.totalPrice + this.shipping - this.pointsDiscount);
			}
    },
		onLoad() {
			// 获取订单预览数据
			const orderPreview = uni.getStorageSync('officeShopOrderPreview');
			if (orderPreview) {
				this.orderData = orderPreview;
				this.calculateTotal();
			}
		},
    onShow() {
      // 获取默认地址
      this.loadDefaultAddress();
    },
		methods: {
			// 加载默认地址
			loadDefaultAddress() {
				// 首先检查是否有选中的地址
				const selectedAddress = uni.getStorageSync('selectedAddress');
				if (selectedAddress) {
					this.address = selectedAddress;
					// 使用完后清除选中的地址，避免影响下次选择
					uni.removeStorageSync('selectedAddress');
					return;
				}
        if (this.userInfo.id) {
          // 如果没有选中的地址，获取默认地址
          this.$api.getDefaultAddress({
            member_user_id: this.userInfo.id
          }).then(res => {
            this.address = res || null
          })
        }
			},
			
			// 选择地址
			selectAddress() {
				// 跳转到地址选择页面
				uni.navigateTo({
					url: '/pages/address/address?select=true'
				});
			},
			
			// 选择支付方式
			selectPaymentType(type) {
				this.paymentType = type;
			},
			
			// 计算总价
			calculateTotal() {
				let price = 0;
				
				this.orderData.products.forEach(item => {
					price += item.price * item.quantity;
				});
				
				this.totalPrice = price;
				
				// 计算运费，这里简单设置为固定运费
				this.shipping = this.totalPrice > 0 ? 10 : 0;
				
				// 重新计算积分抵扣
				this.calculatePointsDiscount();
			},
			
			// 切换积分抵扣
			togglePointsUsage(e) {
				this.usePointsEnabled = e.detail.value;
				this.calculatePointsDiscount();
			},
			
			// 计算积分抵扣金额
			calculatePointsDiscount() {
				if (this.usePointsEnabled) {
					// 使用最大可用积分
					this.pointsDiscount = this.maxPointsDiscount;
				} else {
					// 不使用积分
					this.pointsDiscount = 0;
				}
			},
			
			// 提交订单
			submitOrder() {
				// 检查地址
				if (!this.address) {
					uni.showToast({
						title: '请选择收货地址',
						icon: 'none'
					});
					
					// 延迟跳转至地址选择页面
					setTimeout(() => {
						this.selectAddress();
					}, 1500);
					return;
				}
				
				// 显示加载提示
				uni.showLoading({
					title: '提交订单中...'
				});
				
				// 构建订单数据
				const orderData = {
					products: this.orderData.products,
					address_id: this.address.id,
					payment_type: this.paymentType,
					remark: this.remark,
					total_price: this.totalPrice,
					points_used: this.pointsUsed,
					points_discount: this.pointsDiscount,
					final_price: this.finalPrice,
					shipping_fee: this.shipping,
					order_number: this.generateOrderNumber()
				};
				
				// 调用创建订单API
				this.$api.createOrder(orderData)
					.then(res => {
						// 隐藏加载提示
						uni.hideLoading();
						
						// 如果是从购物车下单，清除已购买的商品
						if (this.orderData.fromCart) {
							this.clearCartItems();
						}
						
						// 清除订单预览数据
						uni.removeStorageSync('officeShopOrderPreview');
						
						// 提示成功
						uni.showToast({
							title: '订单提交成功',
							icon: 'success'
						});
						
						// 跳转到支付页面
						setTimeout(() => {
							uni.navigateTo({
								url: `/pages/order/payment?order_number=${orderData.order_number}&order_id=${res.id}`
							});
						}, 1500);
					})
					.catch(err => {
						// 隐藏加载提示
						uni.hideLoading();
						
						// 提示错误
						uni.showToast({
							title: err.message || '订单提交失败',
							icon: 'none'
						});
					});
			},
			
			// 生成订单号
			generateOrderNumber() {
				const date = new Date();
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const random = Math.floor(Math.random() * 1000000).toString().padStart(6, '0');
				
				return `OS${year}${month}${day}${random}`;
			},
			
			// 清除购物车中已购买的商品
			clearCartItems() {
				const cartList = uni.getStorageSync('officeShopCart') || [];
				const newCartList = cartList.filter(cartItem => {
					// 检查该购物车项是否在订单中
					return !this.orderData.products.some(orderItem => 
						orderItem.id === cartItem.id
					);
				});
				
				// 保存新的购物车
				uni.setStorageSync('officeShopCart', newCartList);
			}
		}
	}
</script>

<style lang="scss">
.container {
	padding-bottom: 120rpx;
}

.address-card {
	background-color: #ffffff;
	padding: 30rpx;
	margin: 20rpx;
	border-radius: 12rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
  margin-bottom: 20rpx;
}

.address-info {
	flex: 1;
}

.address-header {
	display: flex;
	margin-bottom: 10rpx;
}

.name {
	font-weight: bold;
	margin-right: 20rpx;
}

.phone {
	color: #666;
}

.address-detail {
	color: #333;
	font-size: 28rpx;
}

.no-address {
	color: #999;
	font-size: 28rpx;
}

.section-title {
	font-size: 30rpx;
	font-weight: bold;
	padding: 20rpx 30rpx;
	border-bottom: 1px solid #f5f5f5;
}

.product-list, .points-section {
	background-color: #ffffff;
	margin: 20rpx;
	border-radius: 12rpx;
	overflow: hidden;
}

.product-item {
	display: flex;
	padding: 20rpx 30rpx;
	border-bottom: 1px solid #f5f5f5;
}

.product-image {
	width: 140rpx;
	height: 140rpx;
	border-radius: 8rpx;
	margin-right: 20rpx;
}

.product-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}

.product-name {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 10rpx;
}

.product-price {
	color: #ff5500;
	font-size: 28rpx;
}

.product-quantity {
	color: #999;
	font-size: 28rpx;
	padding-top: 50rpx;
}

.points-content {
	padding: 20rpx 30rpx;
}

.points-toggle {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.points-info {
	display: flex;
	flex-direction: column;
	font-size: 28rpx;
}

.points-available {
	margin-top: 10rpx;
	color: #999;
	font-size: 24rpx;
}

.payment-section, .remark-section {
	background-color: #ffffff;
	margin: 20rpx;
	border-radius: 12rpx;
	overflow: hidden;
  padding-bottom: 20rpx;
}

.payment-options {
	padding: 20rpx 30rpx;
}

.payment-option {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1px solid #f5f5f5;
}

.payment-option:last-child {
	border-bottom: none;
}

.payment-option.active {
	color: #007aff;
}

.order-amount {
	background-color: #ffffff;
	margin: 20rpx;
	border-radius: 12rpx;
	padding: 20rpx 30rpx;
}

.amount-item {
	display: flex;
	justify-content: space-between;
	padding: 15rpx 0;
	font-size: 28rpx;
	color: #666;
}

.points-detail {
	justify-content: flex-start;
	padding-top: 0;
}

.points-used-text {
	font-size: 24rpx;
	color: #999;
}

.amount-item.total {
	margin-top: 10rpx;
	padding-top: 20rpx;
	border-top: 1px solid #f5f5f5;
	font-weight: bold;
	color: #333;
}

.total-price {
	color: #ff5500;
}

.discount-price {
	color: #ff5500;
}

.footer {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 100rpx;
	background-color: #ffffff;
	display: flex;
	align-items: center;
	padding: 0 30rpx;
	z-index: 100;
}

.footer-price {
	flex: 1;
	display: flex;
	align-items: center;
}

.price {
	color: #ff5500;
	font-size: 32rpx;
	font-weight: bold;
	margin-right: 10rpx;
}

.submit-btn {
	background-color: #007aff;
	color: #ffffff;
	padding: 0 60rpx;
	height: 80rpx;
	line-height: 80rpx;
	border-radius: 40rpx;
	font-size: 30rpx;
}
</style>
